<template>
  <div class="content q-pa-sm">
    <table-basic :title="'商品管理'" :columns="columns" :tableData="tableData" :searchName="searchName"
                 @searchHandler="searchHandler"
                 @Refresh="Refresh"
                 @updateTable="updateTable"
                 @filtersHandler="filtersHandler"
                 @onDbclick="onDbclick"
    >
      <template v-slot:toolbar>
        <div class="row q-gutter-sm">
          <q-btn color="secondary" label="添加商品" @click="alert=true"  />
          <q-btn color="negative" :disable="checkState <= 0" label="批量删除" @click="deleteHandler"  />
        </div>
      </template>
    </table-basic>

    <form-basic :alert="alert" @close="close" :from="from" :title="'商品管理-添加'"
                @submit="submit"
                @uploadedImage="uploadedImage"
                @removedImage="removedImage"
                state="1"
    ></form-basic>
    <form-basic :alert="updatealert" @close="close" :from="from" :title="'商品管理-修改'"
                @submit="update"
                @uploadedImage="uploadedImage"
                @removedImage="removedImage"
                state="2"
    ></form-basic>
  </div>
</template>

<script>
  import {getProductList,addProduct,removeProduct, updateProduct} from 'src/api/product'
  import { getClassList } from 'src/api/class'
  export default {
    name: "index",
    data () {
      return {
        alert: false,
        updatealert: false,
        options: [],
        from:[
          {
            type: 'string', title: '商品标题', class: '', required: true, style: '', field: 'title',
            rule: [ val=> !!val || '请输入商品标题']
          },
          {
            type: 'select', title: '商品分类', class:'', options: [], style: 'width: 200px',field: 'categoryId'
          },
          {
            type: 'number', title: '商品原价', class: '', required: true, style: 'width: 200px',field: 'origPrice',
            rule: [ val=> !!val || '请输入商品原价']
          },
          {
            type: 'number', title: '商品售价', class: '', required: true, style: 'width: 200px',field: 'sellPrice',
            rule: [ val=> !!val || '请输入商品售价']
          },
          {
            type: 'number', title: '商品排序', class: '', required: true, style: 'width: 200px',field: 'showOrder',
            rule: [ val=> !!val || '请输入商品排序']
          },
          {
            type: 'number', title: '赠送积分数量', class: '', required: true, style: 'width: 200px',field: 'awardPointNum',
            rule: [ val=> !!val || '请输入赠送积分数量']
          },
          {
            type: 'detail', title: '详情内容', class: 'col', style: '', field: 'detailContent'
          },
          {
            type: 'file', title: '商品大图', uploadTitle: '推荐尺寸300*300', required: true, style: '', class:'col',field: 'imageUrls', maxFiles: 10
          },
          {
            type: 'select', title: '限时抢购商品', class:'', options:[{value: 1, label: '是'},{value: 2, label: '否'}], style: 'width: 200px',field: 'isLimitTime',

          },
          {
            type: 'select', title: '商品类型', class:'',options:[{value: 1, label:'购享积分'},{value: 2, label: '购享品质'}], style: 'width: 200px',field: 'type'
          },
          {
            type: 'select', title: '状态', class:'',options:[{value: 1, label:'在售'},{value: 2, label: '下架'}], style: 'width: 200px',field: 'state'
          }
        ],
        tableData:[],
        deleteDisable:true,
        searchName:[
          {key: 'state',label:'商品状态',type:'select',options: [{label:'全部',value:0},{label:'在售',value:1},{label:'下架',value:2}], filter: {label:'全部',value:0}},
          {key: 'title',label:'商品标题',type:'string',filter: ''},
          {key: 'number',label:'商品编号',type:'string',filter: ''},
          {key: 'type',label:'商品类型',type:'select',options: [{label:'全部',value:0},{label:'购享积分',value:1},{label:'购享品质',value:2}], filter: {label:'全部',value:0}}
        ],
        searchFilter: {},
        columns: [
          {name:'select', field: 'select'},
          {name: 'imageUrl', label: '商品大图', field: 'imageUrl',style: 'width: 120px;height: 120px'},
          {name: 'number', align: 'center', label: '商品编号', field: 'number', sortable: true},
          {name: 'title',align: 'center', label: '商品标题', field: 'title'},
          // {name: 'collectNum', align: 'center',label: '收藏数', field: 'collectNum', sortable: true},
          // {name: 'currentPointNum',align: 'center', label: '当前积分数', field: 'currentPointNum', sortable: true},
          // {name: 'totalPointNum',align: 'center', label: '总需积分数量', field: 'totalPointNum', sortable: true},
          {name: 'awardPointNum',align: 'center', label: '赠送积分数量', field: 'awardPointNum', sortable: true},
          // {name: 'minPointNum',align: 'center', label: '最小积分数量', field: 'minPointNum', sortable: true},
          {name: 'origPrice',align: 'center', label: '商品原价', field: 'origPrice', sortable: true},
          {name: 'sellNum',align: 'center', label: '销量', field: 'sellNum', sortable: true},
          {name: 'sellPrice',align: 'center', label: '商品售价', field: 'sellPrice', sortable: true},
          {name: 'type',align: 'center', label: '商品类型',format: (val, row) => `${val==1?'购享积分':val==2?'购享品质':val==3?'抽奖商品':''}`, field: 'type', sortable: true},
          {name: 'state',align: 'center', label: '状态',format: (val, row) => `${val==1?'在售':val==2?'下架':''}`, field: 'state', sortable: true},
          {name: 'isLimitTime',align: 'center', label: '是否是限时抢购商品',format: (val, row) => `${val!==0?'是':'否'}`, field: 'isLimitTime', sortable: true},
          {name: 'isDelete',align: 'center', label: '是否删除', field: 'isDelete', format: (val, row) => `${val!==0?'是':'否'}`, sortable: true},
          {name: 'createTime',align: 'center', label: '创建时间', field: 'createTime',  sortable: true},
        ],
        page: {
          limit: 30,
          page: 1
        },
        categoryList: [],
        imageUrl: []
      }
    },
    mounted() {
      this.initialize()
    },
    components: {
      TableBasic: () => import('components/tables/TableBasic'),
      FormBasic: () => import('components/dialog/formBasic')
    },
    methods:{
      initialize(page,limit){
        if(page)
          this.page.page = page
        if(limit)
          this.page.limit = limit
        let params = Object.assign(this.page, this.searchFilter)
        getProductList(params).then(
          success=>{
            this.tableData = success.records.map(item=>{
              item.select = false
              return item
            })
            this.$bus.$emit('UPDATE_PAGINATION', success.total)
          }
        )
        getClassList({}).then(response => {
          response.forEach((row,index) => {
            this.categoryList.push({label: row.name, value: row.id})
          })
          this.from[1].options = this.categoryList
        })

      },
      onDbclick(index){
        this.updatealert = true
        this.updateData = this.tableData[index];
        this.$bus.$emit('updateState', this.updateData)
      },
      updateTable ({page, rowsPerPage, sortBy}){
        this.initialize(page, rowsPerPage)
      },
      uploadedImage(response){
        this.imageUrl.push(response.data)
      },
      removedImage(response){
        this.imageUrl = this.imageUrl.filter(r=>r !== response.data)
      },
      submit(data){
        let params = Object.assign(data,{
        })
        addProduct(params).then(
          success=>{
            this.alert = false
            this.initialize()
          }
        )
      },
      update(data){
        let params = Object.assign(data,{
          id: this.updateData.id
        })
        updateProduct(params).then(
          success=>{
            this.updatealert = false
            this.initialize()
          }
        )
      },
      deleteHandler(){
        let deleteids = this.checkItems.join(',')
        removeProduct({ids: deleteids}).then(
          success=>{
            this.initialize()
          }
        )
      },
      filtersHandler(filter){
        this.searchFilter = filter;
        this.initialize();
      },
      searchHandler(filter){

      },
      Refresh(){
        this.initialize();
      },
      checkRows(flag){
        console.log(flag)
      },
      close(){
        this.alert = false
        this.updatealert = false
      }
    },
    computed:{
      checkState: function () {
        return this.tableData.reduce((prev, cur) => {
          return prev + (cur.select? 1: 0)
        }, 0)
      },
      checkItems: function () {
        return this.tableData.filter(r=>r.select).map(n=>{
          return n.id
        })
      }
    },
    created() {
      this.$bus.$on('checkRows', this.checkRows)
    },
    beforeDestroy() {
      this.$bus.$off('checkRows', this.checkRows)
    },
  }
</script>

<style scoped>

</style>
